<template>
	<view class="container">
		<view v-if="operable" class="face-wrap">
			<view class="title">请将人脸对准镜头</view>
			<view class="camera-frame">
				<image class="camera-img" src="../../static/img/camera-frame.png" mode="widthFix"></image>
				<camera class="camera"
					device-position="front" 
					frame-size="large" 
					output-dimension="1080P" 
					flash="off" 
					resolution="high"
					@initdone="onInitdone"
					@stop="onStop"
					@error="onError"></camera>
				<view class="icon" v-if="cameraInited">
					<uni-icons custom-prefix="iconfont" type="icon-avartar-border" size="220" color="#FFFFFF"></uni-icons>
				</view>	
			</view>
		</view>
		<view v-else class="tip-text">您已完成认证！</view>
		<view class="operation" v-if="!submited && operable">
			<view v-if="active" class="start-wrap">
				<view class="start-button" @click="submit">确认提交</view>
			</view>
			<view v-else class="timer-wrap">
				<view class="time" :class="{'active':timeer}">{{timeer?time:'--'}}</view>
				<view class="text">倒计时</view>
			</view>
		</view>
		<view class="operation" v-else-if="operable">
			<view class="start-wrap">
				<view class="start-button" @click="start">重新认证</view>
			</view>
		</view>
		<view class="content-wrap">
				<view class="title-bar">
					<image class="title-img" src="../../static/img/title/title_jbxx.png" mode="widthFix"></image>
				</view>
				
				<view class="card info-card">
					<view class="row" v-for="info in infos">
						<view class="label">{{info.name}}</view>
						<view class="value">{{info.value?info.value:''}}</view>
					</view>
				</view>
				
			</view>
			
			<!-- <view class="button" @click="start">确认提交</view> -->
		</view>
	</view>
</template>

<script>
	import { ApiIdentifySchedulePerson } from "@/api/identify/index.js";
	import Store from '@/store/index.js';
	import { pathToBase64 } from '@/js_sdk/mmmm-image-tools/index.js';
	import Config from '@/config/index.js';
	import { ApiResource } from '@/api/application/index.js';
	
	export default {
		data() {
			return {
				user: {},
				schedulePerson:{
					id: null
				},
				scheduleId: null,
				operable: false,	//是否可操作：认证成功或审批通过（不可操作），其它可（重复）操作
				person: {},
				active: false,
				time: 10,
				timeCount: 10,
				timeer: null,  	//定时器
				pictureCount: 3,
				pictures: [],	//抓拍照片（3张）
				video: null,	//短视频
				frames: [],		//人脸帧数据
				infos: [],
				submited: false,
				ctx: null,
				cameraInited: false		//相机加载完成
			}
		},
		created() {
			this.user = this.$store.getUser();
		},
		onLoad(option) {
			this.scheduleId = option.scheduleId;
			if(option.id){
				this.schedulePerson.id = option.id;
				//服务人员操作：
				this.person = {
					personId: option.personId,
					name: option.name,
					idNumber: option.idNumber,
				}
				this.setInfo({...option});
			} else {
				//受助人员自己操作：
				this.person = {
					personId: this.user.id,
					name: this.user.name,
					idNumber: this.user.idNumber,
				}
				this.setInfo(this.user);
			}
			//获取安排名单ID：判断是否以提交有效认证
			this.getSchedulePerson();
		},
		onUnload() {
			if(this.timeer){
				clearTimeout(this.timeer);
			}
			uni.hideLoading();
		},
	
		methods: {
			
			//查询按排名单认证记录
			getSchedulePerson(){
				ApiIdentifySchedulePerson.list({
					scheduleId: this.scheduleId,
					personId: this.person.personId,
				}).then(res=>{
					this.schedulePerson = res.data[0];
					res.data.forEach(item=>{
						//是否可操作：认证成功或审批通过（不可操作），其它可（重复）操作
						if(item.identifyResult == '0' || item.checkStatus=='通过'){
							this.operable = false;
						} else {
							this.operable = true;
						}
						this.setIdentifyResult(item.identifyMessage?item.identifyMessage:'未认证');
						this.setCheckResult(item.checkResult?item.checkResult:'未审核');
					})
					//最多提交次数
					let config = this.$store.getAreaConfig();
					if(res.data[0].submitTimes>config.maxRecognitionTimes){
						this.operable = false;
						uni.showModal({
							title: '认证未成功',
							content: '未通过认证，请等待审核即可。'
						})
					}
				})
			},
			
			//获取网络资源：提示语音
			getSpeech(){
				ApiResource.getByCode('prompts_speech').then(res=>{
					var music = uni.createInnerAudioContext(); 
					music.src = res.data.fileUrl; 
					music.play();
					music.onEnded(() => {
						music = null;
					});
				})
			},
			
			onInitdone(event){
				console.log(event);
				this.cameraInited = true;
				this.active = false;
				//获取提示语音
				this.getSpeech();
				if(!this.ctx){
					this.ctx = uni.createCameraContext();
				}
				this.start();
			},
			onStop(event){
				console.log(event);
			},
			onError(event){
				console.log(event);
			},
			
			start(){
				let that = this;
				that.submited = false;
				// that.countDown();
				// return;
				
				setTimeout(() => {
				    this.ctx.startRecord({
				        // timeout: 10,
				        success:function(){
				        	//倒数计时
				        	that.countDown();
				        	console.log('开始视频录制...');
				        },
				        fail:function(){
				        	console.log('开始视频录制失败');
							// that.start(); 	// 启动失败，重新
				        },
						timeoutCallback : (res) => { 	// 录像超30S或onHide时结束录像
							that.video = res.tempVideoPath;
							console.log('录像超10S或onHide时结束录像');
				       },
				    })
				}, 100)
			},
			
			//拍照
			takePhoto() {
				console.log('准备拍照......')
				let that = this;
				if(that.ctx){
					console.log('可以拍照......')
					that.ctx.takePhoto({
						quality: 'high',
						success: (res) => {
							pathToBase64(res.tempImagePath).then(base64 => {
								console.log('完成拍照......')
								console.log(base64);
								that.pictures.push(base64);
							}).catch(error => {
								console.error(error)
							})
						}
					});
				} else {
					// that.pictures.push(IMG);
				}
			},
			
			//停止视频录制
			stopRecord(){
				let that = this;
				let ctx = that.ctx;
				console.log('停止录频')
				if(ctx){
					setTimeout(() => {
						ctx.stopRecord({
							compressed: true,
							success:function(res){
								that.video = res.tempVideoPath;
							},
							fail:function(e){
								console.log('结束视频录制失败');
								console.log(e);
							},
							complete:function(){
								//
								that.time = that.timeCount;
								clearTimeout(that.timeer);
								that.timeer = null;
								that.active = true;
								uni.hideLoading();
							}
						});
					}, 200);
				}
			},
			
			countDown(){ 
				let that = this;
		 　　　 this.timeer = setTimeout(() => {
					if(this.time == 5 || this.time == 3 || this.time == 1){
						// this.takePhoto();
					}
					this.time--;
					if (this.time < 1) {
						uni.showLoading({
							title: '请点击确认提交按钮，进行认证',
							mask: false
						})
						this.stopRecord();
						// this.time = this.timeCount;
						// clearTimeout(this.timeer);
						// this.timeer = null;
						// this.active = true;
					} else {
						this.countDown();
					}
			    }, 1000);
			},
			
			setInfo(obj){
				this.infos = [{
					name: '真实姓名',
					value: obj.name
				},{
					name: '身份证号',
					value: obj.idNumber
				},{
					name: '认证结果',
					value: '未认证'
				},{
					name: '审核结果',
					value: '未审核'
				}];
			},
			
			setIdentifyResult(value){
				this.infos[2].value = value;
			},
			setCheckResult(value){
				this.infos[3].value = value;
			},
			
			submit(){
				let that =this;
				this.active = false;
				this.submited = true;
				uni.showLoading({
					title: '认证中，请等待...',
					mask: true
				})
				uni.uploadFile({
					header: {
						'Authorization': 'Bearer ' + this.$store.getToken()
					},
					url: Config.baseUrl + '/app/identify/schedule/person/identify',
					filePath: this.video,
					name: 'file',
					formData: {
						...this.person,
						id: this.schedulePerson.id,
						scheduleId: this.schedulePerson.scheduleId,
						submitTimes: this.schedulePerson.submitTimes+1
					},
					success(resopnse) {
						if(resopnse.statusCode==200){
							let res = JSON.parse(resopnse.data);
							if(res.code == 200){
								that.schedulePerson.submitTimes = that.schedulePerson.submitTimes+1;
								that.setIdentifyResult(res.data.identifyMessage?res.data.identifyMessage:'未认证');
								that.setCheckResult(res.data.checkResult?res.data.checkResult:'未审核');
								if(res.data.identifyResult == '0'){
									that.operable = false;
									that.active = false;
									uni.showModal({
										title: '认证成功',
										content: '已通过认证，请返回。'
									})
								}else{
									if(that.schedulePerson.submitTimes>20){
										//超过20次
										that.operable = false;
										uni.showModal({
											title: '认证未成功',
											content: '未通过认证，请等待审核即可。'
										})
									}else{
										that.operable = true;
										uni.showModal({
											title: '认证未成功',
											content: '未通过认证，您可尝试重新认证。'
										})
									}
								}
								//返回刷新标志
								uni.setStorageSync('person-check-status-change', true);
							} else {
								that.operable = true;
								uni.showToast({
									icon: 'error',
									title: '提交失败，请重试'
								})
							}
						}else{
							that.operable = true;
							uni.showToast({
								icon: 'error',
								title: '提交失败，请重试'
							})
						}
					},
					fail(err) {
						that.operable = true;
						uni.showToast({
							icon: 'error',
							title: '提交失败，请重试'
						})
					},
					complete() {
						uni.hideLoading();
					}
				})
			},
			
		},
	}
</script>

<style>
	.container {
		width: 100vw;
	}
	.face-wrap{
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.face-wrap .title{
		font-size: 16px;
		font-weight: bold;
		color: #333333;
		margin-top: 40upx;
		margin-bottom: 0upx;
	}
	.camera-frame{
		position: relative;
	}
	.camera-frame .camera-img{
		width: 750upx;
		height: 750upx;
	}
	.camera-frame .camera{
		width: 480upx;
		height: 480upx;
		border-radius: 240upx;
		position: absolute;
		top: 135upx;
		left: 135upx;
	}
	.camera-frame .icon{
		width: 480upx;
		height: 480upx;
		border-radius: 240upx;
		position: absolute;
		top: 135upx;
		left: 135upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.operation{
		height: 80upx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.start-wrap{
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.start-wrap .start-button{
		width: 240upx;
		padding: 30upx 0;
		text-align: center;
		border-radius: 50upx;
		color: white;
		font-size: 16px;
		font-weight: bold;
		background: linear-gradient(to bottom, #FF8218, #FFAA00 );
	}
	.timer-wrap{
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.timer-wrap .time{
		font-size: 20px;
		font-weight: bold;
		color: #999999;
	}
	.timer-wrap .active{
		color: #FF7B00;
	}
	.timer-wrap .text{
		font-size: 16px;
		font-weight: bold;
		margin-top: 10upx;
	}
	.content-wrap{
		width: 750upx;
		padding: 30upx;
		box-sizing: border-box;
	}
	.title-bar{
		margin-bottom: 30upx;
	}
	.title-bar .title-img{
		width: 180upx;
	}
	.info-card{
		font-size: 14px;
	}	
	.info-card .row{
		display: flex;
		align-items: center;
		padding: 15upx 0;
		font-size: 14px;
	}
	.info-card .row .label{
		color: #999999;
	}
	.info-card .row .value{
		color: #333333;
		display: flex;
		justify-content: right;
		align-items: center;
		margin-left: 20upx;
		font-weight: bold;
	}
	.button{
		margin: 40upx;
		padding: 20upx;
		text-align: center;
		border-radius: 50upx;
		color: white;
		background: linear-gradient(to bottom, #FF8218, #FFAA00 );
	}
	.tip-text{
		width: 100%;
		margin-top: 60upx;
		margin-bottom: 60upx;
		font-size: 20px;
		color: #333333;
		font-weight: bold;
		text-align: center;
	}
</style>
